package com.trsj.lnsj.service.imp;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.bouncycastle.asn1.ocsp.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.controller.ActivityController;
import com.trsj.lnsj.entity.ActivityDTO;
import com.trsj.lnsj.entity.ActivityRepo;
import com.trsj.lnsj.entity.GroupDTO;
import com.trsj.lnsj.entity.GroupRepo;
import com.trsj.lnsj.entity.OrderDTO;
import com.trsj.lnsj.entity.OrderRepo;
import com.trsj.lnsj.entity.Participants;
import com.trsj.lnsj.entity.SignupRecord;
import com.trsj.lnsj.entity.SignupRecordRepo;
import com.trsj.lnsj.mapper.ActivityMapper;
import com.trsj.lnsj.mapper.SignupRecordMapper;
import com.trsj.lnsj.mapper.UserMapper;
import com.trsj.lnsj.util.IDGenerate;
import com.trsj.lnsj.util.ResponseHelper;

@Service
public class ActivityService {
	  private Logger logger = LoggerFactory.getLogger(ActivityService.class);
    @Autowired
    private ActivityMapper actMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SignupRecordMapper signupRecordMapper;
    @Autowired
    private ActivityRepo actRepo;
    @Autowired
    private GroupRepo gropRepo;
    @Autowired
    private OrderRepo orderRepo;
    @Autowired
    private SignupRecordRepo signupRecordRepo;

    
    
    
    /**
     * 查询活动信息
     * 
     * @param act
     * @return
     */
    public DataResponse selectActivityInfo(ActivityDTO act) {
        DataResponse res = null;
        try {
            List<ActivityDTO> actList = actMapper.selectActivityInfo(act);
            res = ResponseHelper.getSuccessResponse(actList);
        } catch (Exception e) {
            res = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return res;
    }

    public DataResponse addActivity(ActivityDTO actDto) {

   
        DataResponse res = null;
        actDto.setActStatus("1");
        actDto.setPrice(actDto.getActAmount());//阿斌肯定要问 为什么要有两个价格，预防以后有活动价格 懂不懂？
        actDto.setCreateDate(new Date());
        actDto.setUpdateDate(new Date());
        try {
            ActivityDTO act = actRepo.saveAndFlush(actDto);
            res = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
        } catch (Exception e) {
            res = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return res;
    }

    public List<ActivityDTO> selectActivityList(ActivityDTO act) {
        List<ActivityDTO> actList = actMapper.selectActivityInfo(act);
        return actList;
    }

    public Page<ActivityDTO> selectActivity(Pageable pageable, String type, String q) {

        Page<ActivityDTO> actList = null;
        if (!StringUtils.isEmpty(type))
            actList = actRepo.findByType(type, pageable);
        else if (!StringUtils.isEmpty(q))
            actList = actRepo.findByNameLikeOrAddressLike("%" + q + "%", "%" + q + "%", pageable);
        else
            actList = actRepo.findAll(pageable);
        return actList;
    }
    public List<ActivityDTO> selectActivityBySQL(int start,int end, String type, String city, String q) {

        List<ActivityDTO> actList = null;
        if (!StringUtils.isEmpty(type))
            actList = actRepo.findByTypeSqlQuery(type, start,end);
        else if (!StringUtils.isEmpty(q))
            actList = actRepo.findByKeyWordSqlQuery("%" + q + "%", start,end);
        else
            actList = actRepo.findAllSqlQuery(start, end);
        return actList;
    }
    //通过mybatis来查询
    public List<ActivityDTO> selectActivity(int start,int end, String type, String city, String q,Float lowprice,Float highprice) {

        List<ActivityDTO> actList = null;
        HashMap<String,Object> map=new HashMap<String,Object>();
         map.put("type", type);
        if (!StringUtils.isEmpty(q))
            map.put("q", "%" + q + "%");
        else
        	map.put("q","");
        map.put("city",city);
        map.put("lowprice",lowprice);
        map.put("highprice",highprice);
        map.put("start",start);
        map.put("end",end);
        actList=actMapper.selectActivity(map);
        return actList;
    }
    
    
    
    public DataResponse updateActivity(ActivityDTO actDto) {
        DataResponse res = null;
        if (actDto.getId() == null) {
            return ResponseHelper.getResponse(MsgStatus.PARAMS_INVALID, "未接收到主键");
        }
        try {
            ActivityDTO actDToRe = actRepo.getOne(actDto.getId());
            if (actDToRe == null) {
                return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "没有这个活动");
            }
            if (!StringUtils.isEmpty(actDto.getName())) {
                actDToRe.setName(actDto.getName());

            }
            if (!StringUtils.isEmpty(actDto.getType())) {
                actDToRe.setType(actDto.getType());
            }
            // #todo 修改是否有条件 如活动开始或者临近开始

            if (actDto.getStartTime() != null & actDto.getStartTime() != null) {

                actDToRe.setStartTime(actDto.getStartTime());
            }

            if (actDto.getEndTime() != null ) {
                actDToRe.setEndTime(actDto.getEndTime());
            }
            if(actDto.getActAmount()!=null) {
            	actDToRe.setActAmount(actDto.getActAmount());
            	actDToRe.setPrice(actDto.getActAmount());
            }
            if(actDto.getContent()!=null) {
            	actDToRe.setContent(actDto.getContent());
            }
            
            actDToRe.setUpdateDate(new Date());
            actRepo.saveAndFlush(actDToRe);
            res = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
        } catch (Exception e) {
        	logger.error("updateActivity修改失败",e);
        	e.printStackTrace();
            res = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return res;
    }

    public DataResponse getUserJoinActivityInfo(int pageNum, int pageSize, String happyNo, short joinType) {
        DataResponse resp = null;
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<ActivityDTO> actList = actMapper.getUserJoinActivityInfo(happyNo, joinType);
            PageInfo<ActivityDTO> page = new PageInfo<ActivityDTO>(actList);
            pageNum = pageNum - 1;
            int total = 0;
            PageRequest pageRequest = new PageRequest(pageNum, pageSize);
            Page<ActivityDTO> page1 = new PageImpl<ActivityDTO>(page.getList(), pageRequest, total);
            resp = ResponseHelper.getSuccessResponse(page1);
        } catch (Exception e) {
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }

    public List<ActivityDTO> findByNameLike(String key) {
        return actRepo.findByNameLike(key);
    }

    /**
     * 
     * <p>
     * Title:
     * </p>
     * <p>
     * Description:
     * </p>
     * <p>
     * Company: 七色环
     * </p>
     * 
     * @author longky
     * @date 20180902 9:30:01
     */
    //todo 报名结束时间
     public String signUp(Long activityId,Long userId,String participants) {
    	  ArrayList<Participants> persons = JSON.parseObject(participants, new TypeReference<ArrayList<Participants>>() {});
    	  ActivityDTO activity=actRepo.getOne(activityId);
    	  List<String> IDNUMS=new ArrayList<String>();
    	  int personNum=persons.size();
    	  for(Participants p :persons) {
    		  IDNUMS.add(p.getIDNUM());
    	  }
    	  if (activity==null) {
    		  return  "-3";//活动不存在
    	  }
    	  List<SignupRecord> record= signupRecordMapper.selectByActivityIDAndIDNUMS(activityId, IDNUMS);
    	
    	if(record.size()>0) {
    		return "-2";
    	}
    	OrderDTO order=new OrderDTO();
    	Date date=new Date();
    	order.setOrderId(IDGenerate.generateUniqueOrderNo(userId.toString()));
    	order.setActivityId(activityId);
    	order.setCreateTime(date);
    	order.setUserId(userId);
    	order.setStatus(0);
    	order.setPersonNum(personNum);
    	order.setPayAmount(activity.getPrice()*personNum);
        int result=actMapper.Signup(activityId,persons.size());//修改报名数量
         if(result==1) {
        	  orderRepo.save(order);
        	 result=signupRecordMapper.insertRecordBatch(userId,activityId,persons,order.getOrderId());}
         else {
        	 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
         }
         return order.getOrderId();
     }

    public DataResponse getFriendActivity(int pageNum, int pageSize, String happyNo) {
        DataResponse resp = null;
        try {
            PageHelper.startPage(pageNum, pageSize);
            List<ActivityDTO> actList = actMapper.getFriendActivity(happyNo);
            PageInfo<ActivityDTO> page = new PageInfo<ActivityDTO>(actList);
            pageNum = pageNum - 1;
            int total = 0;
            PageRequest pageRequest = new PageRequest(pageNum, pageSize);
            Page<ActivityDTO> page1 = new PageImpl<ActivityDTO>(page.getList(), pageRequest, total);
            resp = ResponseHelper.getSuccessResponse(page1);
        } catch (Exception e) {
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }

	public DataResponse listMyCreatedActivity(String actOrganiser, PageRequest pageRequest) {
		// TODO Auto-generated method stub
        DataResponse resp = null;
		  try {
	            Page<ActivityDTO> actList = actRepo.findByActOrganiser(actOrganiser,pageRequest);
	            resp = ResponseHelper.getSuccessResponse(actList);
	        } catch (Exception e) {
	        	e.printStackTrace();
	        	logger.error("listMyCreatedActivity查询创建的活动失败",e);
	        	resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
	        }
	        return resp;
	    }
	public DataResponse findById(Long id) {
		// TODO Auto-generated method stub
        DataResponse resp = null;
		  try {
	            ActivityDTO ActivityDTO = actRepo.getOne(id);
	            resp = new DataResponse(MsgStatus.STATUS_OK,ActivityDTO);
	        } catch (Exception e) {
	        	e.printStackTrace();
	        	logger.error("findById查询活动ById失败",e);
	        	resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
	        }
	        return resp;
	    }
	
	 /**
     * 查询活动信息
     * 
     * @param act
     * @return
     */
    public List<ActivityDTO> moreActivity(Long activityId,String happyNO,Integer start,Integer end) {
    	 List<ActivityDTO> actList =null;
    	try {
         actList = actMapper.moreActivity(activityId,happyNO, start, end);
        } catch (Exception e) {
           logger.error(e.getMessage(),e);
        }
        return actList;
    }
}
